//
//  CMRegistCtrl.m
//  CreditManger
//
//  Created by 于会海 on 15/10/30.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMRegistCtrl.h"
#import "CMAgreementCtrl.h"
#import "CMVerCodeCtrl.h"
#import "CMGetRegMobileCodeParam.h"
#import "CMGetRegMobileCodeParser.h"
#import "CMGetRegMobileCodeInfo.h"
#import "UIImageView+WebCache.h"
#import "CheckValid.h"

@interface CMRegistCtrl ()<UITextFieldDelegate>

@property (assign, nonatomic) BOOL isReback;
@property (strong, nonatomic) UITextField* graphCode;
@property (strong, nonatomic) UIView* secLine;
@property (strong, nonatomic) UIButton* reGraphBtn;
@property (strong, nonatomic) UIView* rgtBackView;
@property (strong, nonatomic) UIView* rgtLine;
@property (strong, nonatomic) UIImageView* codeImageView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topBackViewHeight;
@property (weak, nonatomic) IBOutlet UIView *topBackView;
@property (weak, nonatomic) IBOutlet UIButton *getCodeButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumFiled;
@property (weak, nonatomic) IBOutlet UITextField *passWordFiled;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
- (IBAction)getPhoneCode:(id)sender;
- (IBAction)getAgreement:(id)sender;
- (IBAction)agreementBtnClicked:(UIButton *)sender;

@end

@implementation CMRegistCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
}
- (void)buildLayout{
    self.title = @"注册";
    [self showDoneWithTitle:@"已有账号"];
    self.phoneNumFiled.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneNumFiled.delegate = self;
    self.passWordFiled.delegate = self;
    self.getCodeButton.layer.cornerRadius = 4;
}

- (void)reGraphBtnClicked:(UIButton*)button{
    [self setCodeImageViewWithCode];
}

- (void)doDone{
    LLog(@"已有账号");
    [self.navigationController popToRootViewControllerAnimated:YES];    
}


#pragma  setGraphCell
- (void)addGraphCellWith{
    if (!self.isReback) {
        self.isReback = YES;
        self.topBackViewHeight.constant = 122;
        [self setCodeImageViewWithCode];
    }else{
        return;
    }

    UIView* secLine = [[UIView alloc] initWithFrame:CGRectMake(10, 81, SCREEN_WIDTH-10, 1)];
    [secLine setBackgroundColor:[LCCommon getColor:@"cccccc"]];
    [self.topBackView addSubview:secLine];
    
    UIImage* graImage = [UIImage imageNamed:@"regist_graphCode"];
    UIImageView* graphImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 92, graImage.size.width, graImage.size.height)];
    graphImage.image = graImage;
    [self.topBackView addSubview:graphImage];
    
    self.graphCode = [[UITextField alloc] initWithFrame:CGRectMake(38, 82, 200, 40)];
    self.graphCode.font = [UIFont systemFontOfSize:12];
    self.graphCode.placeholder = @"请输入图形验证码";
    self.graphCode.delegate = self;
    [self.topBackView addSubview:self.graphCode];
    
    self.reGraphBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    self.reGraphBtn.frame = CGRectMake(SCREEN_WIDTH - 60, 84, 50, 35);
    self.reGraphBtn.tintColor = [LCCommon getColor:@"666666"];
    [self.reGraphBtn setTitle:@"换一张" forState:UIControlStateNormal];
    [self.reGraphBtn addTarget:self action:@selector(reGraphBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.topBackView addSubview:self.reGraphBtn];
    
    UIView* rgtBackView= [[UIView alloc] initWithFrame:CGRectMake(self.reGraphBtn.frame.origin.x-70-5, 89, 70, 24)];
    rgtBackView.layer.borderColor = [LCCommon getColor:@"cccccc"].CGColor;
    rgtBackView.layer.borderWidth = 1;
    [self.topBackView addSubview:rgtBackView];
    
    self.codeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, rgtBackView.frame.size.width, rgtBackView.frame.size.height)];
    [self setCodeImageViewWithCode];
    [rgtBackView addSubview:self.codeImageView];
    
    UIView* rgtLine = [[UIView alloc] initWithFrame:CGRectMake(rgtBackView.frame.origin.x-10, 81, 1, 40)];
    [rgtLine setBackgroundColor:[LCCommon getColor:@"cccccc"]];
    [self.topBackView addSubview:rgtLine];
}

- (void)setCodeImageViewWithCode{
    NSString* gid = [self getGID];
    NSMutableString* urlString =  [[NSMutableString alloc] init];
    [urlString appendFormat:@"%@gid=%@",@"http://192.168.50.222:6088/koudai_server/user/getRegImageCode.do?",gid];
    [self.codeImageView setImageWithURL:[NSURL URLWithString:urlString]  placeholderImage:nil options:SDWebImageRefreshCached];
}

# pragma textField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (self.phoneNumFiled == textField){
        if ([toBeString length] > 10){
            textField.text = [toBeString substringToIndex:11];
            [textField resignFirstResponder];
            return NO;
        }
    }
    if (self.passWordFiled == textField) {
        if ([toBeString length] > 17) {
            textField.text = [toBeString substringToIndex:18];
            [textField resignFirstResponder];
            return NO;
        }
    }
    if (self.graphCode == textField) {
        if ([toBeString length] > 5) {
            textField.text = [toBeString substringToIndex:6];
            [textField resignFirstResponder];
            return NO;
        }
    }
    return YES;
}

# pragma setDodownBtn
- (IBAction)agreementBtnClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.agreeBtn.selected = sender.selected;
}
- (IBAction)getPhoneCode:(id)sender {
    if (![CheckValid isValidatePhone:self.phoneNumFiled.text]){
        [self.phoneNumFiled becomeFirstResponder];
        DISSMISS_ERRView(@"手机号输入不正确",[[[UIApplication sharedApplication] windows] lastObject]);
        return;
    }
    if([CheckValid checkStrIsEmpty:self.passWordFiled.text]){
        [self.passWordFiled becomeFirstResponder];
        DISSMISS_ERRView(@"用户密码不能为空",[[[UIApplication sharedApplication] windows] lastObject]);
        
    }else if (self.passWordFiled.text.length < 6){
        
        [self showMobileCodeAlert];
        return;
    }
    if (self.agreeBtn.selected == NO){
        
        [self  showAgreementAlert];
        return;
    }
    if (self.isReback == YES) {
        
        if (self.graphCode.text.length < 4) {
            [self  showGraphAlert];
            return;
        }
    }
    [self requestToGetPhoneCode];
}

- (void)requestToGetPhoneCode{
    CMGetRegMobileCodeParam* param = [[CMGetRegMobileCodeParam alloc] init];
    param.mobile = self.phoneNumFiled.text;
    param.gid = [self getGID];
    if (self.isReback == YES) {
        param.imageCode = self.graphCode.text;
    }
    CMGetRegMobileCodeParser* parser = [[CMGetRegMobileCodeParser alloc] init];
    [NetCenter postDataFromURL:Method_getRegMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            LLog(@"验证码已发送");
            
            CMGetRegMobileCodeInfo* info = (CMGetRegMobileCodeInfo*)myResult.result;
            
            __weak CMRegistCtrl* weakSelf = self;
            CMVerCodeCtrl* verCodeVC = [[CMVerCodeCtrl alloc] init];
            verCodeVC.phoneNum = self.phoneNumFiled.text;
            verCodeVC.password = self.passWordFiled.text;
            verCodeVC.phoneVerCode = info.mobileCode;
            verCodeVC.doBackBlock = ^(BOOL isBack){
                if (isBack == YES) {
                    [weakSelf addGraphCellWith];
                }
            };
            [self.navigationController pushViewController:verCodeVC animated:YES];
        }
        if (myResult.code == 1) {
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (NSString*)getGID{
    NSUUID *identifierForVendor = [[UIDevice currentDevice] identifierForVendor];
    NSString *deviceId = [identifierForVendor UUIDString];
    return deviceId;
}

- (IBAction)getAgreement:(id)sender {
    LLog(@"进入金信网服务协议");
    CMAgreementCtrl* agreeVC = [[CMAgreementCtrl alloc] init];
    [self.navigationController pushViewController:agreeVC animated:YES];
}

- (void)showPhoneNumAlert{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"输入手机号码有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showMobileCodeAlert{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"密码长度不足6位" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showAgreementAlert{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请您阅读《金信网服务协议》" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showGraphAlert{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"图形验证码输入有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.agreeBtn.selected = NO;
    self.phoneNumFiled.text = @"";
    self.passWordFiled.text = @"";
    self.graphCode.text = @"";
    self.navigationController.navigationBarHidden = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
